package com.example.filter;

import com.alibaba.fastjson.JSON;
import com.example.common.BaseContext;
import com.example.common.R;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import java.io.IOException;
@Slf4j
@WebFilter(filterName = "LoginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    public static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();//路径匹配器，支持通配符
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        //获取本次请求的uri
        String uri = request.getRequestURI();
        log.info("本次请求的路径："+uri);
        //定义访问时候不需要处理的页面
        String[] urls=new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login"
        };
        //判断本次请求是否需要处理
        if(check(urls,uri))
        {
            log.info("不需要处理的："+uri);
            filterChain.doFilter(request,response);
            return;
            //不需要处理直接放行
        }
        else {
            if(request.getSession().getAttribute("employee")!=null)//判断是否登录
            {
                filterChain.doFilter(request,response);//登陆了就放行
                Long id = (Long) servletRequest.getAttribute("employee");
                BaseContext.setCurrentId(id);
                log.info("登录的id："+id);
                return;
            }
            if(request.getSession().getAttribute("user")!=null)//判断是否登录
            {
                filterChain.doFilter(request,response);//登陆了就放行
                Long id = (Long) servletRequest.getAttribute("user");
                BaseContext.setCurrentId(id);
                log.info("登录的id："+id);
                return;
            }

                response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));//没登陆则返回
                log.info("未登录"+uri);
                return;
        }
    }
    public  boolean check(String[] urls,String uri)
    {
        for (String url : urls) {
            if(PATH_MATCHER.match(url,uri))
            {
                return true;//进行匹配
            }
        }
        return false;
    }
}
